package com.card.user;

import java.util.Vector;

import org.jboss.netty.channel.ChannelHandlerContext;

import com.card.admin.FeedBackManager;
import com.card.admin.ServerManager;
import com.card.admin.pojo.Admin;
import com.card.admin.pojo.AdminManager;
import com.card.common.CardContants;
import com.card.common.MessageComm;
import com.card.game.BasePlayer;
import com.card.game.BasePlayer.UserState;
import com.card.game.Player;
import com.card.game.ddz.DdzPlayBack;
import com.card.game.pdk.PdkPlayBack;
import com.card.game.playback.PlayBackManager;
import com.card.game.playback.Playback;
import com.card.game.room.AbstractRoom;
import com.card.game.room.RoomManager;
import com.card.game.room.RoomState;
import com.card.game.room.SHRoom;
import com.card.log.LogType;
import com.card.log.LogUtils;
import com.card.match.Match;
import com.card.match.MatchManager;
import com.card.message.JsonMessageCenter;
import com.card.setting.GameSetting;
import com.card.user.UserCurrency.CurrencyKind;
import com.xiaoao.net.global.Global;
import com.xiaoao.net.json.IMsgProcesser;
import com.xiaoao.net.json.Router;
import com.xiaoao.net.json.message.JsonMessage;
import com.xiaoao.net.utils.AddressUtils;
import com.xiaoao.net.utils.StringUtil;
import com.xiaoao.net.utils.Validator;

public class UserLogic implements IMsgProcesser {
	private static final UserLogic instance = new UserLogic();

	public static UserLogic getInstance() {
		return instance;
	}

	@Override
	public void registMsgId() {
		Router.getInstance().registMsg(MessageComm.C2S_Login, this);
		Router.getInstance().registMsg(MessageComm.C2S_SubmitAdvice, this);
		Router.getInstance().registMsg(MessageComm.C2S_UserPing, this);
		Router.getInstance().registMsg(MessageComm.C2S_FreindInfo, this);
		Router.getInstance().registMsg(MessageComm.C2S_RemoveMail, this);
		Router.getInstance().registMsg(MessageComm.C2S_SHRoomPlayBack, this);
		Router.getInstance().registMsg(MessageComm.C2S_DayReward, this);
		Router.getInstance().registMsg(MessageComm.C2S_LeaveRoom, this);
		Router.getInstance().registMsg(MessageComm.C2S_Exchange, this);
		Router.getInstance().registMsg(MessageComm.C2S_Type_Request, this);
		Router.getInstance().registMsg(MessageComm.C2S_Feedback, this);
		Router.getInstance().registMsg(MessageComm.C2S_Share_Reward, this);
		Router.getInstance().registMsg(MessageComm.C2S_JiaBei, this);
		Router.getInstance().registMsg(MessageComm.C2S_Real_Auth, this);
		Router.getInstance().registMsg(MessageComm.C2S_Father_Id, this);
		Router.getInstance().registMsg(MessageComm.C2S_GPS, this);
	}

	@Override
	public void doProcess(int msgId, JsonMessage serverMsg, ChannelHandlerContext ctx) {
		switch (msgId) {
		case MessageComm.C2S_Login:
			userLogin(serverMsg, ctx);
			break;
		case MessageComm.C2S_SubmitAdvice:
			userSubmitAdvice(serverMsg, ctx);
			break;
		case MessageComm.C2S_UserPing:
			userPing(serverMsg, ctx);
			break;
		case MessageComm.C2S_FreindInfo:
			friendInfo(serverMsg, ctx);
			break;
		case MessageComm.C2S_RemoveMail:
			removeMail(serverMsg, ctx);
			break;
		case MessageComm.C2S_SHRoomPlayBack:
			getPlayback(serverMsg, ctx);
			break;
		case MessageComm.C2S_DayReward:
			dayReward(serverMsg, ctx);
			break;
		case MessageComm.C2S_LeaveRoom:
			leaveRoom(serverMsg, ctx);
			break;
		case MessageComm.C2S_Exchange:
			exchange(serverMsg, ctx);
			break;
		case MessageComm.C2S_Type_Request:
			typeRequest(serverMsg, ctx);
			break;
		case MessageComm.C2S_Feedback:
			feedback(serverMsg, ctx);
			break;
		case MessageComm.C2S_Share_Reward:
			shareReward(serverMsg, ctx);
			break;
		case MessageComm.C2S_JiaBei:
			jiabei(serverMsg, ctx);
			break;
		case MessageComm.C2S_Real_Auth:
			realNameAuth(serverMsg, ctx);
			break;
		case MessageComm.C2S_Father_Id:
			yaoQingMa(serverMsg, ctx);
			break;
		case MessageComm.C2S_GPS:
			fuzhigps(serverMsg, ctx);
			break;
		}
	}
	
	//gps赋值
	private void fuzhigps(JsonMessage serverMsg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();
		//经度  纬度
		double longitude = serverMsg.getAsDouble("longitude");
		double latitude = serverMsg.getAsDouble("latitude");
		System.out.println(longitude+"精度   唯独"+latitude);
		//user.setGps(longitude);
		//user.setGps2(latitude);
		
	}

	public void userLogin(JsonMessage serverMsg, ChannelHandlerContext ctx) {
		String name = serverMsg.getAsString("name");
		String wechatPlatform = serverMsg.getAsString("wechatPlatform");
		// 进行处理
		int versionCode = serverMsg.getAsInt("vcode");
		int loginType = serverMsg.getAsInt("loginType");
		if (!ServerManager.getInstance().checkLogin(loginType, versionCode, ctx)) {
			return;
		}
		// 进行处理
		User user = UserUtils.getUserByImei(name);
		user.userExtra().updateInfo(wechatPlatform);
		user.setCtx(ctx); // 用户上绑定socket
		ctx.setAttachment(user);// socket 上绑定

		user.startMessageQueue();
		// 检查短线room
		AbstractRoom room = getRoom(user);
		user.setRoom(room);
		Match match = MatchManager.getInstance().getMatchById(user.getMatchId());
		user.setMatch(match);

		JsonMessage message = new JsonMessage(MessageComm.S2C_Login);
		user.fillMsg(message);
		message.addProperty("dayReward", user.userStorage().isDayReward());
		message.addProperty("haveRoom", room != null);
		message.addProperty("haveMatch", match != null);
		JsonMessageCenter.getInstance().sendMessage(message, user);

		// 检查短线重连
		if (room != null) {
			// 短线重链接
			Global.logCommMessage("=============断线重连=====================");
			BasePlayer player = room.getPlayerById(user.getPrimaryKey());
			player.setUser(user);
			room.breakConnect(player);
			return;
		}
		if (match != null) {
			match.checkUserMatch(user);
			return;
		}
		String ip = user.getIp();
		user.userExtra().setAddress(AddressUtils.getRegion(ip));
		user.sendUserUpdateMessage();
	}

	private void yaoQingMa(JsonMessage serverMsg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();
		int fatherId1 = user.getFatherId();
		if (fatherId1 == 0) {
			int fatherId = serverMsg.getAsInt("fatherId");
			System.out.println(fatherId);
			Admin admin = AdminManager.getInstance().getAdmin(fatherId + "");
			if (admin != null) {
				user.addCharmValue(fatherId);
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "添加成功！");
				return;
			} else {
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "不是代理，请重新输入！");
			}
		}
	}

	private void realNameAuth(JsonMessage serverMsg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		String cardId = serverMsg.getAsString("cardId");
		String name = serverMsg.getAsString("name");
		if (user.userExtra().isRealNameAuth()) {
			JsonMessageCenter.getInstance().sendEorrorMessage(user, "您已经实名认证");
			return;
		}
		if (StringUtil.NullOrEmpty(cardId) || !Validator.isIDCard(cardId)) {
			JsonMessageCenter.getInstance().sendEorrorMessage(user, "身份证格式错误");
			return;
		}
		if (StringUtil.NullOrEmpty(name)) {
			JsonMessageCenter.getInstance().sendEorrorMessage(user, "真实姓名格式错误");
			return;
		}
		user.userExtra().realNameAuth(cardId, name);
		int rewardGold = GameSetting.getInstance().getBinCard();
		user.userCurrency().add(CurrencyKind.Diamonds, rewardGold);
		LogUtils.addSpendLog(user, LogType.BindCard, rewardGold);

		user.sendUserUpdateMessage();
		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_Real_Auth);
		message.addProperty("gold", rewardGold);
		JsonMessageCenter.getInstance().sendMessage(message, user);
	}

	/**
	 * 检查是否有相同的角色重复登录
	 * 
	 * @param userId
	 */
	public void chkSameUserLogin(String userId) {
		User oldUser = UserManager.getInstance().getUserByKey(userId);
		if (oldUser != null) {
			if (oldUser.isOnline()) {
				Global.logErrorMessage("账号重复登录!!!!" + userId);
				JsonMessage message = new JsonMessage(MessageComm.S2C_SameUserLogin);
				message.addProperty("msg", "此账号重复登录,您被断开连接");
				com.xiaoao.net.json.message.JsonMessageCenter.getInstance().sendMessage(message, oldUser.getCtx());
			}
			userLoginOut(oldUser);
		}
	}

	private AbstractRoom getRoom(User user) {
		int roomId = user.getRoomId();
		if (roomId > 1) {
			AbstractRoom tempRoom = RoomManager.getInstance().getRoomById(roomId);
			System.out.println(tempRoom);
			if (tempRoom != null) {
				BasePlayer player = tempRoom.getPlayerById(user.getPrimaryKey());
				if (player != null) {
					return tempRoom;
				}
			}
		}
		return null;
	}

	private void userSubmitAdvice(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		String content = msg.getAsString("content");
		// 处理反馈信息
		int result = user.userAdvice().submitAdvice(content);
		// 向玩家发送反馈结果信息
		JsonMessage message = new JsonMessage(MessageComm.S2C_SubmitAdvice);
		message.addProperty("result", result);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	private void userPing(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();
		JsonMessage message = new JsonMessage(MessageComm.S2C_UserPing);
		message.addProperty("time", msg.getAsFloat("time"));
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
		if (user != null) {
			user.setPing();
		}
	}

	private void friendInfo(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		String friendId = msg.getAsString("fid");
		System.out.println(friendId);
		User friend = UserUtils.getUserByPrimaryKey(friendId);
		if (friend == null) {
			JsonMessageCenter.getInstance().sendEorrorMessage(user, "好友不存在!");
			return;
		}
		friendInfo4(msg,friendId,ctx);
		JsonMessage message = new JsonMessage(MessageComm.S2C_FreindInfo);
		friend.fillFriendMsg(message);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}
	
	private void friendInfo4(JsonMessage msg, String friendId, ChannelHandlerContext ctx) {
		//User user = (User) ctx.getAttachment();// 玩家信息
		User user = UserUtils.getUserByPrimaryKey(friendId);
		Vector<BasePlayer> playerList = user.getRoom().getPlayerList();
		System.out.println(user.getPrimaryKey());

		JsonMessage message = new JsonMessage(MessageComm.S2C_FreindInfo4);
		for (int i=0;i<playerList.size();i++) {
			BasePlayer basePlayer = playerList.get(i);
			System.out.println(user.getPrimaryKey());
			if (!user.getPrimaryKey().equals(basePlayer.getUser().getPrimaryKey())) {
				String username = basePlayer.getUser().getUserExtra().getNickName();
				String ip = basePlayer.getIp();
				System.out.println(ip +"------"+username+"------"+basePlayer.getUser().getPrimaryKey());
				message.addProperty("freindInfo"+i,"#"+ username+":"+ip+"#");
			}
		}
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	private void removeMail(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		String mailId = msg.getAsString("id");
		user.userMail().removeMail(mailId);
		user.sendUserUpdateMessage();
	}

	private void getPlayback(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		String id = msg.getAsString("id");
		int type = msg.getAsInt("type");

		if (type == CardContants.GAMETYPE_SH) {
			Playback playback = PlayBackManager.getInstance().getPlayback(id);
			if (playback == null) {
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "录像不存在");
				return;
			}
			JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_SHRoomPlayBack);
			message.addProperty("playback", playback);
			message.addProperty("type", type);
			JsonMessageCenter.getInstance().sendMessage(message, ctx);
		} else if (type == CardContants.GAMETYPE_SH) {
			DdzPlayBack playback = PlayBackManager.getInstance().getDdzPlayback(id);
			if (playback == null) {
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "录像不存在");
				return;
			}
			JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_SHRoomPlayBack);
			message.addProperty("playback", playback);
			message.addProperty("type", type);
			JsonMessageCenter.getInstance().sendMessage(message, ctx);
		} else {
			PdkPlayBack playback = PlayBackManager.getInstance().getPdkPlayback(id);
			if (playback == null) {
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "录像不存在");
				return;
			}
			JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_SHRoomPlayBack);
			message.addProperty("playback", playback);
			message.addProperty("type", type);
			JsonMessageCenter.getInstance().sendMessage(message, ctx);
		}
	}

	private void dayReward(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		if (!user.userStorage().isDayReward()) {
			return;
		}
		user.userCurrency().add(CurrencyKind.Gold, GameSetting.getInstance().getDayRewardGold());
		user.userStorage().setDayReward(false);
		user.sendUserUpdateMessage();
		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_DayReward);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	private void exchange(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		int gold = user.userCurrency().get(CurrencyKind.Gold);
		int scale = GameSetting.getInstance().getExchangeScale();
		int diamond = gold / scale;
		int tureGold = diamond * scale;
		if (tureGold == 0 || !user.userCurrency().spend(CurrencyKind.Gold, tureGold)) {
			JsonMessageCenter.getInstance().sendEorrorMessage(user, "金币不满足兑换要求");
			return;
		}
		user.userCurrency().add(CurrencyKind.Diamonds, diamond);
		user.sendUserUpdateMessage();
		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_Exchange);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	// 离开房间
	private void leaveRoom(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		SHRoom room = (SHRoom) user.getRoom();
		if (room != null) {
			if (room.isStartGame() || room.getState() != RoomState.Wait) {
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "比赛已经开始,不能退出房间");
				return;
			}
			if (StringUtil.equals(room.getOwnerId(), user.getPrimaryKey())) {
				JsonMessageCenter.getInstance().sendEorrorMessage(user, "房主不能退出房间");
				return;
			}
			room.leaveRoom(user.getPrimaryKey());
		}
		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_LeaveRoom);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	private void typeRequest(JsonMessage msg, ChannelHandlerContext ctx) {
		int vcode = msg.getAsInt("vcode");
		int touristCode = GameSetting.getInstance().getTouristCode();
		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_Type_Request);
		// message.addProperty("type", vcode==touristCode?1:0);
		// 测试更改为
		message.addProperty("type", vcode == touristCode ? 1 : 1);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	private void feedback(JsonMessage msg, ChannelHandlerContext ctx) {
		String phone = msg.getAsString("phone");
		String content = msg.getAsString("content");

		FeedBackManager.getInstance().save(phone, content);

		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_Feedback);
		JsonMessageCenter.getInstance().sendMessage(message, ctx);
	}

	private void shareReward(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		int type = msg.getAsInt("type");
		int gold = user.userStatistics().shareCanReward(type);
		if (gold > 0) {
			user.userCurrency().add(CurrencyKind.Diamonds, gold);
			user.sendUserUpdateMessage();

			JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_Share_Reward);
			message.addProperty("gold", gold);
			message.addProperty("type", type);
			JsonMessageCenter.getInstance().sendMessage(message, user);
			if (type == 1) {
				LogUtils.addSpendLog(user, LogType.Share1, gold);
			} else {
				LogUtils.addSpendLog(user, LogType.Share2, gold);
			}
		}
	}

	private void jiabei(JsonMessage msg, ChannelHandlerContext ctx) {
		User user = (User) ctx.getAttachment();// 玩家信息
		int bei = msg.getAsInt("bei");
		SHRoom room = (SHRoom) user.getRoom();
		if (room != null) {
			Player player = room.getPlayerById(user.getPrimaryKey());
			if (player.isCanJiaBei) {
				player.jiaBei(bei);
				player.setState(UserState.Ready);
				System.out.println("UserLogic:" + player.nickName + "_" + player.jiaBei);
				room.sendRoomBei();
				if (room.checkCanSieve()) {
					room.randomSieve();
				}
			}
		}
	}

	/**
	 * 玩家退出游戏后的处理
	 * 
	 * @param user
	 */
	public void userLoginOut(User user) {
		if (user == null)
			return;
		user.loginOut();
		UserManager.getInstance().removeUser(user);
		ChannelHandlerContext ctx = user.getCtx();
		if (ctx != null) {
			user.setCtx(null);
			ctx.setAttachment(null);
			// ctx.getChannel().disconnect();
			ctx.getChannel().close();
		}
	}
}
